#include "DatagramSocket.h"

DatagramSocket::DatagramSocket() {
    DatagramSocket("127.0.0.1", 9000);
}

DatagramSocket::DatagramSocket(unsigned short port) {
    DatagramSocket("127.0.0.1", port);
}

DatagramSocket::DatagramSocket(const char* address, unsigned short port) {
    this->address = address;
    this->port = port;
}

DatagramSocket::~DatagramSocket() {
    Unbind();
}

void DatagramSocket::Bind() {
    struct sockaddr_in localAddress;
    
    WSAData wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);
    
    s = socket(AF_INET, SOCK_DGRAM, 0);
    localAddress.sin_family = AF_INET;
    localAddress.sin_addr.S_un.S_addr = INADDR_ANY;
    localAddress.sin_port = htons(this->port);
    
    bind(s, (struct sockaddr *) &localAddress, sizeof(localAddress));
}

void DatagramSocket::Bind(unsigned short port) {
    this->port = port;
    
    Bind();
}

bool DatagramSocket::isBound() {
    return bound;
}

void DatagramSocket::Unbind() {
    closesocket(s);
    WSACleanup();
}

void DatagramSocket::Send(const DatagramPackage* datagram) {
    
}

void DatagramSocket::Receive(const DatagramPackage* datagram) {
    char buffer[512];    
    int received;
    
    struct sockaddr_in remoteAddress;
    int remoteAddressLength = sizeof(remoteAddress);
    
    for (;;) {
        received = recvfrom(s, buffer, sizeof(buffer), 0, (struct sockaddr *) &remoteAddress, &remoteAddressLength);
        printf("Received from '%s:%d '\n", inet_ntoa(remoteAddress.sin_addr), ntohs(remoteAddress.sin_port));
        printf("Data: %s", buffer);
        
        Sleep(100);
    }
}
